<?php

use App\Constants\ErrorCode;
use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;

if (!function_exists('container')) {
    /**
     * 获取容器实例
     * @return ContainerInterface
     */
    function container(): ContainerInterface
    {
        return ApplicationContext::getContainer();
    }
}
if (!function_exists('redis')) {
    /**
     * 获取Redis实例
     * @return \Hyperf\Redis\Redis
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function redis(): \Hyperf\Redis\Redis
    {
        return container()->get(\Hyperf\Redis\Redis::class);
    }
}
if (!function_exists('console')) {

    /**
     * 获取控制台输出实例
     * @return StdoutLoggerInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function console(): StdoutLoggerInterface
    {
        return container()->get(StdoutLoggerInterface::class);
    }

}
if (!function_exists('logger')) {
    /**
     * 获取日志实例
     * @param string $name
     * @return LoggerInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    function logger(string $name = 'Log',$group = 'default'): LoggerInterface
    {
        return container()->get(LoggerFactory::class)->get($name);
    }
}

if (!function_exists('json_e')) {
    function json_e($value): bool|string
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * json返回
 */
if (!function_exists('json_res')) {
    function json_res($data, $const, $code, $new_msg): bool|string
    {
        list($action, $msg) = $const;
        $arr = [
            'action' => $action,
            'action_msg' => $const[1],
            'msg' => empty($new_msg) ? ErrorCode::getMessage($code) : $new_msg,
            'data' => $data,
            'code' => $code,
        ];
        return json_e($arr);
    }
}

/**
 * json_解码
 */
if (!function_exists('json_d')) {
    function json_d($data): mixed
    {
        return json_decode($data, true);
    }
}

/**
 * 数组合并
 */
if (!function_exists('array_merge_self')) {
    function array_merge_self(array $data): array
    {
        $res = [];
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $res = array_merge($res, $val);
            }
        }
        return $res;
    }
}
